using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FreeLancer.HRB.Domains;
using FreeLancer.HRB.Services;
using DevExpress.Web.ASPxUploadControl;
using FreeLancer.HRB.Core;
using DevExpress.Web.ASPxClasses;
using FreeLancer.HRB.Core.Services;
using System.Xml;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.Data;

namespace FreeLancer.HRB.WebApp.Admin.Pages
{
  public partial class Events : System.Web.UI.Page
  {
    #region Members

    private TList<FreeLancer.HRB.Domains.Events> _events;
    private int _languageId;

    #endregion

    #region Page Events

    protected void Page_Init(object sender, EventArgs e)
    {
      SessionWrapper.SetSession(Session);

      LoadLanguage();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      InitializeData();
    }

    #endregion

    #region ASPxGridViewEvents Events

    protected void ASPxGridViewEvents_OnHtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
    {
      if (e.RowType != GridViewRowType.Data) return;
      bool isPublished = Convert.ToBoolean(ASPxGridViewEvents.GetRowValuesByKeyValue(e.KeyValue, "IsPublished"));
      if (!isPublished)
      {
        e.Row.BackColor = System.Drawing.Color.FromArgb(255, 200, 200);
      }
    }

    protected void ASPxGridViewEvents_OnDeleting(object sender, ASPxDataDeletingEventArgs e)
    {
      if (e.Keys["EventId"] != null)
      {
        EventsService eventsService = GlobalCache.EventsService;

        Guid id = (Guid)e.Keys["EventId"];

        try
        {
          using (ConnectionScope.CreateTransaction())
          {
            eventsService.Delete(id, _languageId);

            InitializeData();

            //Because do not use the SqlDataSource, 
            //so the grid do not have normal delete method.
            //Can handle it by canceling and going back to browser mode.
            e.Cancel = ConnectionScope.Complete();
          }
        }
        catch (Exception ex)
        {
          LoggingService.LogCritical("Admin-Events Page", "Exception when delete Events",
              ex, LoggingService.DefaultCategory, true);
        }
      }
    }

    protected void ASPxGridViewEvents_OnUpdating(object sender, ASPxDataUpdatingEventArgs e)
    {
      if (e.Keys["EventId"] != null)
      {
        EventsService eventsService = GlobalCache.EventsService;
        Guid id = (Guid)e.Keys["EventId"];

        FreeLancer.HRB.Domains.Events evnt = _events.Find("EventId", id);

        if (evnt != null)
        {
          evnt.IsPublished = (bool)e.NewValues["IsPublished"];
          evnt.Title = e.NewValues["Title"] as string;
          evnt.DateModified = DateTime.Now;

          try
          {
            using (ConnectionScope.CreateTransaction())
            {
              eventsService.Save(evnt);

              InitializeData();

              //Because do not use the SqlDataSource, 
              //so the grid do not have normal update method.
              //Can handle it by canceling and going back to browser mode.
              e.Cancel = ConnectionScope.Complete();
              ASPxGridViewEvents.CancelEdit();
            }
          }
          catch (Exception ex)
          {
            LoggingService.LogCritical("Admin-Events Page", "Exception when update Events",
              ex, LoggingService.DefaultCategory, true);
          }
        }
      }
    }

    #endregion

    #region cboLanguage Events

    protected void cboLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    #endregion

    #region Page Processing

    /// <summary>
    /// Initialize language to combobox
    /// </summary>
    private void LoadLanguage()
    {
      int total = 0;
      LanguagesService languageService = new LanguagesService();
      TList<Languages> languages = languageService.GetPaged("IsActive='True'", string.Empty, 0, 3, out total);
      cboLanguage.DataSource = languages;
      cboLanguage.DataTextField = "Name";
      cboLanguage.DataValueField = "LanguageID";
      cboLanguage.DataBind();
    }

    /// <summary>
    /// Initialize for GridView Post
    /// </summary>
    private void InitializeData()
    {
      if (cboLanguage.SelectedIndex >= 0)
      {
        _languageId = int.Parse(cboLanguage.SelectedValue);
        SessionWrapper.LanguageId = _languageId;

        try
        {
          //Get event by languageID
          int total = 0;
          EventsService service = GlobalCache.EventsService;
          _events = service.GetPaged("LanguageID=" + _languageId, string.Empty, 0, 10000, out total);

          ASPxGridViewEvents.DataSource = _events;
          ASPxGridViewEvents.DataBind();

          ASPxGridViewEvents.SortBy(ASPxGridViewEvents.Columns["DateModified"],
            DevExpress.Data.ColumnSortOrder.Descending);
        }
        catch (Exception ex)
        {
          LoggingService.LogCritical("Admin-Events Page", "Exception when get Events",
            ex, LoggingService.DefaultCategory, true);
        }
      }
      else
      {
        LoggingService.LogCritical("Admin-Events Page", "There is no language when load Events",
              null, LoggingService.DefaultCategory, true);
      }
    }

    #endregion
  }
}
